package com.dissertation.service.impl;

import com.alibaba.fastjson.JSON;
import com.dissertation.pojo.Message;
import com.dissertation.service.IDownload;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
import com.sun.mail.util.MimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@Service
public class GridSFDownload implements IDownload {

    @Autowired
    GridFsTemplate gridFsTemplate;

    @Override
    public void download(String id, HttpServletResponse response, HttpServletRequest request) throws IOException {
        OutputStream outputStream = response.getOutputStream();
        GridFSDBFile fsFile = gridFsTemplate.findOne( new Query( Criteria.where( "_id" ).is( id ) ) );

        if ( fsFile == null ) {
            outputStream.write( JSON.toJSONBytes( Message.createErr( "对不起， 该文件不存在" ) ) );
        }
        response.setHeader("Content-Type", fsFile.getContentType());
        String filename = fsFile.getFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));

        if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
            filename = URLEncoder.encode(filename, "UTF-8");
        } else {
            filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);

        response.setHeader("type", suffix);
        fsFile.writeTo( outputStream );
        outputStream.close();
    }
}
